﻿using EntityFrameworkCore.Triggered;
using Microsoft.EntityFrameworkCore;
using StockTrading.Triggers;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StockTrading.Model
{
    public class ApplicationDbContext: TriggeredDbContext
    {
        private readonly DbContextOptions<ApplicationDbContext> options;

        public DbSet<User> Users { get; set; }
        public DbSet<Stock> Stocks { get; set; }
        public DbSet<Transaction> Transactions { get; set; }
        public DbSet<Order> Orders { get; set; }                                                                                                                             
        public DbSet<UserPosition> UserPositions { get; set; }



        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //设置表名
            modelBuilder.Entity<User>()
                .ToTable("users");
            modelBuilder.Entity<Stock>()
                .ToTable("stock");
            modelBuilder.Entity<Order>()
                .ToTable("order");
            modelBuilder.Entity<Transaction>()
                .ToTable("transaction");
            modelBuilder.Entity<UserPosition>()
                .ToTable("user_position");

            //设置外键关系,OnDelete解决循环依赖问题，如果出现删除order表中数据而不删除transaction相关内容，saveChanges会报错
            modelBuilder.Entity<Transaction>()
                .HasOne(x => x.Sell_Order)
                .WithMany(o => o.SellTransactionsList)
                .HasForeignKey(y => y.Sell_OrderId)
                .OnDelete(DeleteBehavior.ClientSetNull);

            modelBuilder.Entity<Transaction>()
                .HasOne(x => x.Buy_Order)
                .WithMany(o => o.BuyTransactionsList)
                .HasForeignKey(y => y.Buy_OrderId)
                .OnDelete(DeleteBehavior.ClientSetNull);
            modelBuilder.Entity<UserPosition>()
                .HasKey(x => new
                {
                    x.StockId,
                    x.UserId
                });

            base.OnModelCreating(modelBuilder);
        }
    }
}
